package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.AlbumMapper;
import cn.tedu.csmall.product.mapper.PictureMapper;
import cn.tedu.csmall.product.pojo.dto.PictureAddNewDTO;
import cn.tedu.csmall.product.pojo.entity.Picture;
import cn.tedu.csmall.product.pojo.vo.AlbumStandardVO;
import cn.tedu.csmall.product.pojo.vo.PictureStandardVO;
import cn.tedu.csmall.product.service.IPictureService;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class PictureServiceImpl implements IPictureService {

    @Autowired
    PictureMapper pictureMapper;
    @Autowired
    AlbumMapper albumMapper;

    @Override
    public void addNew(PictureAddNewDTO dto) {
        log.debug("开始处理[添加图片业务], 参数:{}",dto);
        //判断图片对应的相册是否存在
        AlbumStandardVO standardById = albumMapper.getStandardById(dto.getAlbumId());
        if (standardById == null) {
            //否: 不存在, 添加失败, 抛出异常
            String message = "图片没有对应的相册, 添加失败";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        //是: 存在, 可以添加
        Picture picture = new Picture();
        BeanUtils.copyProperties(dto, picture);
        log.debug("准备添加图片, 参数:{}", picture);
        int i = pictureMapper.insert(picture);
        if (i != 1) {
            String message = "添加失败, 服务器忙, 请稍后再试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理[删除图片业务], 参数:{}",id);
        //判断图片是否存在
        PictureStandardVO standardPictureById = pictureMapper.getStandardPictureById(id);
        if (standardPictureById == null) {
            //否: 图片不存在, 删除失败, 抛出异常
            String message = "删除失败, 图片不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        //是: 图片存在, 可以删除
        int i = pictureMapper.deleteById(id);
        if (i != 1) {
            String message = "删除失败, 服务器忙, 请稍后再试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }
}
